package com.fubowen.reader.extension

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.text.Editable
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat

fun TextView.setRightDrawable(resIs: Int = 0, color: Int = 0, padding: Int = PADDING_SM) {
   if(resIs != 0){
       val drawable = ContextCompat.getDrawable(context, resIs)
       compoundDrawablePadding = padding
       drawable?.setColor(color)
       setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
   }else{
       setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
   }
}

fun TextView.setLeftDrawable(resIs: Int = 0, color: Int = 0, padding: Int = PADDING_SM) {
    if (resIs != 0) {
        val drawable = ContextCompat.getDrawable(context, resIs)
        compoundDrawablePadding = padding
        drawable?.setColor(color)
        setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
    } else {
        setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
    }
}

fun TextView.setGradientDrawable(
    color: Int,
    radius: Int = RADIUS_SM,
    strokeWidth: Int = STROKE_SM
) {
    setTextColor(color)
    GradientDrawable().apply {
        shape = GradientDrawable.RECTANGLE
        cornerRadius = radius.toFloat()
        setStroke(strokeWidth, color)
        background = this
    }
}

fun EditText.replace(content: CharSequence): Editable =
    text.replace(selectionStart, selectionEnd, content)

fun EditText.replaceAll(content: CharSequence): Editable = text.replace(0, text.length, content)
fun EditText.setEmpty() = setText("")

fun EditText.hideSoftInput() {
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE)
    if (imm is InputMethodManager) {
        imm.hideSoftInputFromWindow(this.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}
